// store/modules/createPayPalOrder.js
import axios from 'axios';

export default {
    namespaced: true,
    state: {
        payPalUrl: null,
        payPalOrderNo: null,
        error: null,
    },
    mutations: {
        SET_PAYPAL_URL(state, url) {
            state.payPalUrl = url;
        },
        SET_PAYPAL_ORDER_NO(state, orderNo) {
            state.payPalOrderNo = orderNo;
        },
        SET_ERROR(state, error) {
            state.error = error;
        },
    },
    actions: {
        async createPayPalOrder({ commit }, paymentData) {
            try {
                const response = await axios.post('order/api/pay/payment/travel', paymentData);

                if (response.data.code === 200) {
                    commit('SET_PAYPAL_ORDER_NO', response.data.data.orderNo);
                    commit('SET_PAYPAL_URL', response.data.data.url);
                    return { success: true,orderNo: response.data.data.orderNo, url: response.data.data.url };
                } else if (response.data.code === 309) {
                    commit('SET_PAYPAL_ORDER_NO', response.data.message);
                    return { success: true,orderNo:response.data.message };
                }else {
                    commit('SET_ERROR', response.data.message || '生成支付单号失败');
                    return { success: false, error: response.data.message || '生成支付单号失败' };
                }
            } catch (error) {
                console.error('生成支付单号失败:', error);
                const errorMessage = '生成支付单号失败，请稍后再试';
                commit('SET_ERROR', errorMessage);
                return { success: false, error: errorMessage };
            }
        },
    },
    getters: {
        getPayPalUrl: state => state.payPalUrl,
        getPayPalOrderNo: state => state.payPalOrderNo,
        getError: state => state.error,
    },
};
